﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;
using System.Web.Script.Serialization;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Diagnostics;
using IWshRuntimeLibrary;

namespace TStart
{
    class Misc
    {
        public static string json_format(string json)
        {
            int indent = 0;
            bool esc_flag = false;
            bool str_flag = false;

            for (int i = 0; i < json.Length; i++)
            {
                if (esc_flag)
                {
                    esc_flag = false;
                }
                else if (json[i] == '\\')
                {
                    esc_flag = true;
                }
                else if (json[i] == '\"')
                {
                    str_flag = !str_flag;
                }
                else if (str_flag)
                {

                }
                else if (json[i] == '{')
                {
                    indent++;
                    string str_tmp = "\r\n" + new string('\t', indent);
                    json = json.Insert(i + 1, str_tmp);
                    i += str_tmp.Length;
                }
                else if (json[i] == '}')
                {
                    indent--;
                    string str_tmp = "\r\n" + new string('\t', indent);
                    json = json.Insert(i, str_tmp);
                    i += str_tmp.Length;
                }
                else if ((json[i] == ',') && (json[i + 1] != '{'))
                {
                    string str_tmp = "\r\n" + new string('\t', indent);
                    json = json.Insert(i + 1, str_tmp);
                    i += str_tmp.Length;
                }
            }

            return json;
        }

        public static string PathFilePath(string path)
        {
            int p = path.LastIndexOf("\\");
            if (p < 0)
            {
                return path;
            }

            return path.Substring(0, p);
        }

        public static string PathFileNameEx(string path)
        {
            int p = path.LastIndexOf("\\");
            if (p < 0)
            {
                return "";
            }

            return path.Substring(p + 1);
        }

        public static string PathFileName(string path)
        {
            int p = path.LastIndexOf("\\");
            if (p < 0)
            {
                return "";
            }

            string str_tmp = path.Substring(p + 1);
            p = str_tmp.LastIndexOf(".");
            if (p < 0)
            {
                return str_tmp;
            }

            return str_tmp.Substring(0, p);
        }

        public static AppsItem PathAppsItem(string path)
        {
            AppsItem appItem = new AppsItem();
            appItem.Name = PathFileName(path);

            if (System.IO.File.Exists(path) && (path.Length > 4)
                && path.Substring(path.Length - 4).ToLower() == ".lnk")
            {
                WshShell shell = new WshShell();
                IWshShortcut shortCut = (IWshShortcut)shell.CreateShortcut(path);
                appItem.Path = shortCut.TargetPath;
                appItem.Args = shortCut.Arguments;
            }
            else
            {
                appItem.Path = path;
                appItem.Args = "";
            }
            appItem.Icon = appItem.Path;

            return appItem;
        }

        /// <summary>  
        /// 更改是否开机自启动
        /// </summary>  
        /// <param name="isAutoStartup">是否开机自启动</param>  
        public static void ChangeAutoStartUp(bool isAutoStartup)
        {
            string programName = Process.GetCurrentProcess().MainModule.ModuleName;
            string executablePath = Process.GetCurrentProcess().MainModule.FileName;

            //自启动注册表路径
            string registryRunPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
            try
            {
                bool isAdmin = IsAdmin();
                //判断当前用户是否是管理员
                RegistryKey registryKey = isAdmin
                    ? Registry.LocalMachine.CreateSubKey(registryRunPath)
                    : Registry.CurrentUser.CreateSubKey(registryRunPath);
                if (registryKey == null) return;
                if (isAutoStartup)
                {
                    registryKey.SetValue(programName, executablePath); //开启自启动
                }
                else
                {
                    registryKey.DeleteValue(programName, false); //关闭自启动
                }
            }
            catch
            {
            }
        }

        public static bool IsAutoStartUp()
        {
            string programName = Process.GetCurrentProcess().MainModule.ModuleName;
            string executablePath = Process.GetCurrentProcess().MainModule.FileName;

            //自启动注册表路径
            string registryRunPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
            try
            {
                bool isAdmin = IsAdmin();
                //判断当前用户是否是管理员
                RegistryKey registryKey = isAdmin
                    ? Registry.LocalMachine.CreateSubKey(registryRunPath)
                    : Registry.CurrentUser.CreateSubKey(registryRunPath);
                if (registryKey == null) return false;
                if(registryKey.GetValue(programName) != null) return true;
            }
            catch
            {
            }

            return false;
        }

        /// <summary>
        /// 判断程序是否以管理员身份运行
        /// </summary>
        /// <returns></returns>
        public static bool IsAdmin()
        {
            bool result = false;
            try
            {
                System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                result = principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
            }
            catch
            {
            }
            return result;
        }
    }
}
